<template>
  <div class="live-room-form">
    <a-form-model
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }">
      <a-form-model-item prop="appId">
        <template slot="label">
          <span style="color: red">*</span>直播平台
        </template>
        <a-radio-group
          :disabled="handle != 'add'"
          v-model="formData.appId"
          @change="appIdChange">
          <a-radio v-for="(item, index) in liveAppIdList" :key="index" :value="item.value" :disabled="(userInfo.shopRoleCode != 'role:store:main') && (item.value == '100000054')">{{ item.label }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item prop="name">
        <template slot="label">
          <span style="color: red">*</span>直播标题
        </template>
        <a-input
          allow-clear
          style="width:415px"
          :disabled="handle == 'view'"
          v-model="formData.name"
          :maxLength="17"
          placeholder="输入直播间标题，限6-34字符，汉字占两个字符" />
      </a-form-model-item>
      <a-form-model-item prop="anchorWechat">
        <template slot="label">
          <span style="color: red">*</span>主播微信账号
        </template>
        <a-select
          :disabled="handle == 'view'"
          v-model="formData.anchorWechat"
          allow-clear
          style="width:415px"
          :options="anchorList"
          @change="anchorChange"
          placeholder="请选择主播"></a-select>
      </a-form-model-item>
      <a-form-model-item prop="anchorName">
        <template slot="label">
          <span style="color: red">*</span>主播对外昵称
        </template>
        <a-input allow-clear
          style="width:415px"
          :disabled="handle == 'view'"
          v-model="formData.anchorName"
          placeholder="输入主播昵称，限4-30字符，汉字占两个字符" />
      </a-form-model-item>
      <a-form-model-item prop="liveTime">
        <template slot="label">
          <span style="color: red">*</span>开播时间
        </template>
        <a-date-picker
                allow-clear
                :disabled="handle == 'view'"
                v-model="formData.startTime"
                :disabled-date="disabledStartDate"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                @openChange="handleStartOpenChange" />
        <span class="date-split"> 至 </span>
        <a-date-picker
                allow-clear
                :disabled="handle == 'view'"
                v-model="formData.endTime"
                :disabled-date="disabledEndDate"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束时间"
                :open="endOpen"
                @openChange="handleEndOpenChange" />
        <p class="form-tips">注：开播时间要设定在至少10分钟以后，所选时间范围必须在30分钟到72小时之间</p>
      </a-form-model-item>
      <a-form-model-item label="基本功能设置">
        <a-button type="primary" class="expand-btn" @click="handleExpand"> {{expandTxt}} </a-button>
        <p class="form-tips">评论、商品货架、分享、点赞、回放和客服功能均默认开启。如需修改点击展开列表</p>
      </a-form-model-item>
      <transition name="normal-expand">
        <div class="info-box" v-show="isShowBox">
          <a-form-model-item label="是否允许评价" prop="closeComment">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeComment">
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="是否允许点赞" prop="closeLike">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeLike">
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="是否允许分享" prop="closeShare">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeShare">
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="是否允许回放" prop="closeReplay">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeReplay">
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="是否展示商品货架" prop="closeGoods">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeGoods">
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="是否允许官方收录" prop="closeRecord">
            <a-radio-group :disabled="handle == 'view'" v-model="formData.closeRecord">
              <a-radio :value="0"> 否 </a-radio>
              <a-radio :value="1"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </div>
      </transition>
      <a-form-model-item prop="shareImgLocal">
        <template slot="label">
          <span style="color: red">*</span>分享卡封面图片
        </template>
        <div class="upload-box">
          <upload-image class="img"
            :disabled="handle == 'view'"
            :fileSizeLimit="1048576"
            v-model="formData.shareImgLocal"
            :afterUploadFun="shareImgLocalAfterUploadFun"></upload-image>
          <div class="upload-txt">
            观众在微信对话框内分享的直播间将以分享卡片的形式呈现。<br>
            建议尺寸：800像素 * 640像素 <br>
            图片大小不得超过1M
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item prop="recordImageLocal">
        <template slot="label">
          <span style="color: red">*</span>官方收录图片
        </template>
        <div class="upload-box">
          <upload-image class="img"
            :disabled="handle == 'view'"
            :fileSizeLimit="102400"
            v-model="formData.recordImageLocal"
            :afterUploadFun="recordImageLocalAfterUploadFun"></upload-image>
          <div class="upload-txt">
            一个好的封面图能帮助用户在购物直播频道更好的辨识出直播间。<br>
            建议尺寸：800像素 * 800像素<br>
            图片大小不得超过100Kb
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item prop="coverImgLocal">
        <template slot="label">
          <span style="color: red">*</span>直播背景墙
        </template>
        <div class="upload-box">
          <upload-image class="img"
            :disabled="handle == 'view'"
            :fileSizeLimit="2097152"
            v-model="formData.coverImgLocal"
            :afterUploadFun="coverImgLocalAfterUploadFun"></upload-image>
          <div class="upload-txt">
            直播间背景墙是每个直播间的默认背景。<br>
            建议尺寸：1080像素 * 1920像素<br>
            图片大小不得超过2M
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-col :offset="2">
          <a-space>
            <a-button :loading="confirmLoading" v-if="handle != 'view'" type="primary" @click="submitData()">提交保存</a-button>
            <a-button @click="handleCancel">{{ handle != 'view' ? '取消' : '返回' }}</a-button>
          </a-space>
        </a-col>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import deepCopy from '@/utils/deepCopy'
import moment from "moment";
import { createOptionsByDict } from '@/utils/dict'
const formData={
  appId: undefined, // 平台编号
  name: undefined, // 直播间名称
  anchorWechat: undefined, // 主播微信
  anchorName: undefined, // 主播名称
  startTime: undefined, // 开始时间
  endTime: undefined, // 结束时间
  liveTime: undefined, // 直播时间
  shareImg: undefined, // 分享图片mediaId
  shareImgLocal: undefined, // 分享图片
  recordImage: undefined, // 官方收录图片mediaId
  recordImageLocal: undefined, // 官方收录图片
  coverImg: undefined, // 直播背景图片mediaId
  coverImgLocal: undefined, // 直播背景图片
  closeComment: 1, // 是否允许评价
  closeLike: 1, // 是否允许点赞
  closeShare: 1, // 是否允许分享
  closeReplay: 1, // 是否允许回放
  closeGoods: 1, // 是否展示商品货架
  closeRecord: 1, // 是否允许官方收录
  phone: undefined // 创建人
}
export default {
  name: 'MarketingLiveRoomPagesForm',
  computed: {
    ...mapGetters(["userInfo"]),
    // 操作类型
    handle() {
      return this.$route.query.handle || "";
    },
    // 直播间id
    id() {
      return this.$route.query.id || "";
    },
    // 直播平台
    appId() {
      return this.$route.query.appId || "";
    },
    // 所属店铺
    blong() {
      return this.$route.query.blong || "";
    },
    // 用户信息
    userInfo(){
      return this.$store.getters.userInfo || {};
    }
  },
  data() {
    return {
      liveAppIdList: createOptionsByDict('LIVE_APPID'), // 直播平台
      headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 接口域名
      uploadUrl: '/product/uploadImage', // 上传接口
      formData, // 表单数据
      rules: {}, // 验证规则
      confirmLoading: false, // 防连点
      expandTxt: '点击展开', // 展开合并文字
      isShowBox: false, // 是否展示隐藏
      endOpen: false, // 结束时间选择器是否打开
      anchorList: [] // 主播列表
    };
  },
  created() {
    this.resetData()
    if(this.id){
      this.getLiveInfo(this.id)
    }
    this.getanchorList()
  },
  mounted() {},
  methods: {
    //重置
    resetData(){
      this.formData=deepCopy(formData);
      if(this.appId) {
        this.formData.appId=this.appId
      } else {
        if(this.$store.state.userInfo.shopRoleCode == 'role:store:main') {
          this.formData.appId=createOptionsByDict('LIVE_APPID')[0] ? createOptionsByDict('LIVE_APPID')[0].value : '100000054'
        } else if(this.$store.state.userInfo.shopRoleCode == 'role:store:branch') {
          this.formData.appId=createOptionsByDict('LIVE_APPID')[1] ? createOptionsByDict('LIVE_APPID')[1].value : '100000055'
        }
      }
    },
    // 切换直播平台
    appIdChange(val) {
      this.getanchorList()
    },
    // 获取所有主播
    async getanchorList() {
      let _this = this
      let res = await this.$get('/user/list',
        {
          appId: _this.formData.appId,
          status: 1
        },
        { baseURL: `${location.origin}/goldenhome/gh/live/admin` });
      if(res && res.returnCode=='1000'){
        if(res.dataInfo){
          this.anchorList = []
          res.dataInfo.forEach(item => {
            let flag = {}
            flag.value = item.anchorWechat
            flag.label = item.anchorWechat
            flag.name = item.anchorName
            _this.anchorList.push(flag)
          })
        }
      }
    },
    // 获取直播间信息
    async getLiveInfo(id) {
      let _this = this
      let res = await this.$get('/room/id',
        {
          appId: _this.formData.appId,
          roomId: id
        },
        { baseURL: `${location.origin}/goldenhome/gh/live/admin` });
      if(res && res.returnCode=='1000'){
        if(res.dataInfo){
          _this.formData = res.dataInfo
        }
      }
    },
    // 选择直播间主播
    anchorChange(val) {
      this.formData.anchorName = this.anchorList.filter( item => item.value===val )[0].name
    },
    // 开始时间不能小于当前时间
    disabledStartDate(current) {
      return current < moment(moment().format('YYYY-MM-DD 00:00:00'))
    },
    // 结束时间不能小于开始时间
    disabledEndDate(current) {
      return current < moment(moment(this.formData.startTime).format('YYYY-MM-DD 00:00:00'))
    },
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    },
    disabledEndDateTime() {
      let hour = moment(this.formData.startTime).format('HH')
      let minute = moment(this.formData.startTime).format('mm')
      let second = moment(this.formData.startTime).format('ss')
      return {
        disabledHours: () => this.range(0, Number(hour)),
        disabledMinutes: () => this.range(0, Number(minute)),
        disabledSeconds: () => this.range(0, Number(second)),
      };
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    // 展开 收起
    handleExpand() {
        this.isShowBox = !this.isShowBox;
        this.expandTxt = this.isShowBox ? '点击收起' : '点击展开';
    },
    // 上传图片
    fileUpload(file, key) {
      this.$upload(this.uploadUrl,
        file,
        {
          ...this.headParams,
          params: {appId: this.formData.appId}
        }).then(res => {
        this.formData[key] = res.dataInfo.mediaId
      })
    },
    // 图片转base64，再转文件流，上传图片
    imgToFile(img, width, height, filename) {
      // 图片转base64
      let canvas = document.createElement("canvas")
      canvas.width = width
      canvas.height = height
      let ctx = canvas.getContext("2d")
      ctx.drawImage(img, 0, 0, width, height)
      let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase()
      let dataURL = canvas.toDataURL("image/" + ext)
      // base转文件流
      let arr = dataURL.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 上传完图片处理数据
    shareImgLocalAfterUploadFun(data) {
      let filename = new Date().valueOf().toString()+'.'+data.url.substring(data.url.lastIndexOf('.') + 1);
      let _this = this
      let image = new Image()
      image.src = data.url
      image.setAttribute("crossOrigin", "Anonymous")
      image.onload = function() {
        if(image.width > 800 || image.height > 640) {
          _this.$message.error('图片宽高不符合规范，请重新上传！');
          return
        } else {
          let file = _this.imgToFile(image, image.width, image.height, filename)
          _this.fileUpload(file, 'shareImg')
          setTimeout(() => {
            _this.formData.shareImgLocal = data.url
          },100)
          // _this.formData.shareImg = data.mediaId
          // _this.formData.shareImgLocal = data.imageDataInfo.url
        }
      }
      console.log(this.formData)
    },
    // 上传完图片处理数据
    recordImageLocalAfterUploadFun(data) {
      let filename = new Date().valueOf().toString()+'.'+data.url.substring(data.url.lastIndexOf('.') + 1);
      let _this = this
      let image = new Image()
      image.src = data.url
      image.setAttribute("crossOrigin", "Anonymous")
      image.onload = function() {
        if(image.width > 800 || image.height > 800) {
          _this.$message.error('图片宽高不符合规范，请重新上传！');
          return
        } else {
          let file = _this.imgToFile(image, image.width, image.height, filename)
          _this.fileUpload(file, 'recordImage')
          setTimeout(() => {
            _this.formData.recordImageLocal = data.url
          },100)
          // _this.formData.recordImage = data.mediaId
          // _this.formData.recordImageLocal = data.imageDataInfo.url
        }
      }
    },
    // 上传完图片处理数据
    coverImgLocalAfterUploadFun(data) {
      let filename = new Date().valueOf().toString()+'.'+data.url.substring(data.url.lastIndexOf('.') + 1);
      let _this = this
      let image = new Image()
      image.src = data.url
      image.setAttribute("crossOrigin", "Anonymous")
      image.onload = function() {
        if(image.width > 1080 || image.height > 1920) {
          _this.$message.error('图片宽高不符合规范，请重新上传！');
          return
        } else {
          let file = _this.imgToFile(image, image.width, image.height, filename)
          _this.fileUpload(file, 'coverImg')
          setTimeout(() => {
            _this.formData.coverImgLocal = data.url
          },100)
          // _this.formData.coverImg = data.mediaId
          // _this.formData.coverImgLocal = data.imageDataInfo.url
        }
      }
    },
    // 返回拼团列表
    back() {
      this.confirmLoading = false
      this.$router.push({
        name: "MarketingLiveRoom",
        query: {
          current:this.$route.query.current||1,
          blong: this.$route.query.blong,
          appId:this.$route.query.appId||this.formData.appId
        }
      });
    },
    // 取消/返回
    handleCancel(){
      this.back()
    },
    // 提交表单
    submitData(){
      // 验证直播间名称
      if(!this.formData.name) {
        return this.$message.error('请输入直播间名称');
      } else {
        let re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则
        const name = this.formData.name
        let length = 0
        if(this.formData.name.match(re)) {
          length = this.formData.name.match(re).length;  //计算中文的个数
        }
        let nameLength = this.formData.name.length + length
        if(nameLength < 6 || nameLength > 34){
          this.formData.name = name
          return this.$message.error('直播间名称长度必须为6-34字符');
        } else {
          this.formData.name = name
        }
      }
      // 验证是否选择主播
      if(!this.formData.anchorWechat) {
        return this.$message.error('请选择主播');
      }
      // 验证主播昵称
      if(!this.formData.anchorName) {
        return this.$message.error('请输入主播昵称');
      } else {
        let re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则
        const anchorName = this.formData.anchorName
        let length = 0
        if(this.formData.anchorName.match(re)) {
          length = this.formData.anchorName.match(re).length;  //计算中文的个数
        }
        let nameLength = this.formData.anchorName.length + length
        if(nameLength < 4 || nameLength > 30){
          this.formData.anchorName = anchorName
          return this.$message.error('主播昵称长度必须为4-30字符');
        } else {
          this.formData.anchorName = anchorName
        }
      }
      // 验证直播时间
      if(!this.formData.startTime) {
        return this.$message.error('请选择直播开始时间');
      }
      if(moment(this.formData.startTime).unix()*10*10*10 < (moment()+10*60*10*10*10)) {
        return this.$message.error('直播开始时间需设置在当前时间10分钟后');
      }
      if (!this.formData.endTime) {
        return this.$message.error('请选择直播结束时间');
      }
      if(moment(this.formData.endTime).unix()*10*10*10 < (moment(this.formData.startTime).unix()*10*10*10+30*60*10*10*10)) {
        return this.$message.error('直播结束时间不能小于直播开始时间后30分钟');
      }
      if(moment(this.formData.endTime).unix()*10*10*10 > (moment(this.formData.startTime).unix()*10*10*10+72*60*60*10*10*10)) {
        return this.$message.error('直播结束时间不能大于直播开始时间后72小时');
      }
      // 验证分享卡封面图片
      if(!this.formData.shareImgLocal) {
        return this.$message.error('请上传分享卡封面图片');
      }
      // 验证官方收录图片
      if(!this.formData.recordImageLocal) {
        return this.$message.error('请上传官方收录图片');
      }
      // 验证直播背景墙
      if(!this.formData.coverImgLocal) {
        return this.$message.error('请上传直播背景墙');
      }
      this.formData.phone = this.userInfo.userPhone
      let url = ''
      switch (this.handle) {
        case 'add':
          url = '/room/addRoom'
          break;
        case 'edit':
          url = '/room/update'
          break;
      }
      this.confirmLoading = true
      this.$post(url,
        this.formData,
        { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
      .then(res => {
        if(res && res.returnCode=='1000'){
          this.back()
          return this.$message.success('保存成功！');
        }
        else{
          this.confirmLoading = false
          return this.$message.error('保存失败！');
        }
      })
      .catch(err => {
        this.confirmLoading = false
      })
    }
  }
};
</script>

<style lang="less">
.live-room-form{
  .upload-box{
    display: flex;
    .img{
      margin-right: 12px;
    }
    .upload-txt{
      line-height: 34px;
    }
  }
}

</style>
